package ru.edu.vstu.atpp.acm.ui.services.authenticator;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Session;
import ru.edu.vstu.atpp.acm.ui.entities.Authors;
import ru.edu.vstu.atpp.acm.ui.security.AuthenticationException;
import ru.edu.vstu.atpp.acm.ui.services.dao.AuthorsDAO;

public class AuthenticatorImpl implements Authenticator {

    public static final String AUTH_TOKEN = "authToken";

    @Inject
    private AuthorsDAO authorsDAO;

    @Inject
    private Request request;

    public void login(String username, String password) throws AuthenticationException {

        Authors user = authorsDAO.findAuthorsByNameAndPassword(username, password);

        if (user == null) {
            throw new AuthenticationException("The user doesn't exist");
        }

        request.getSession(true).setAttribute(AUTH_TOKEN, user);
    }

    public boolean isLoggedIn() {
        Session session = request.getSession(false);
        if (session != null) {
            return session.getAttribute(AUTH_TOKEN) != null;
        }
        return false;
    }

    public void logout() {
        Session session = request.getSession(false);
        if (session != null) {
            session.setAttribute(AUTH_TOKEN, null);
            session.invalidate();
        }
    }

    public Authors getLoggedUser() {
        Authors user;

        if (isLoggedIn()) {
            user = (Authors) request.getSession(true).getAttribute(AUTH_TOKEN);
        } else {
            throw new IllegalStateException("The user is not logged ! ");
        }
        return user;
    }
}
